package com.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.dto.MedicineDTO;
import com.demo.dto.R;
import com.demo.entity.Category;
import com.demo.entity.Medicine;
import com.demo.service.CategoryService;
import com.demo.service.MedicineService;
import com.demo.util.MyPage;
import com.demo.vo.CategoryMedicineVO;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (Medicine)表控制层
 *
 * @author Sakura
 * @since 2023-11-26 17:11:07
 */
@Api(value = "/api/medicine", tags = {"(Medicine)表控制层"})
@RestController
@RequestMapping("/api/medicine")
@CrossOrigin
public class MedicineController {
    /**
     * 服务对象
     */
    @Resource
    private MedicineService medicineService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询
     *
     * @param pageNo    当前页
     * @param pageSize  数据大小
     * @param searchKey 查询参数
     * @return 查询结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageNo", value = "当前页", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageSize", value = "数据大小", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchKey", value = "查询参数")
    })
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "GET")
    @GetMapping("/list/{pageNo}/{pageSize}")
    public R<MyPage<MedicineDTO>> queryByPage(@PathVariable Integer pageNo,
                                              @PathVariable Integer pageSize,
                                              @RequestParam(required = false) String searchKey) {
        return R.success(this.medicineService.queryByPage(pageNo, pageSize, searchKey));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "通过主键查询单条数据", notes = "通过主键查询单条数据", httpMethod = "GET")
    @GetMapping("{id}")
    public R<Medicine> queryById(@PathVariable("id") Long id) {
        Medicine medicine = this.medicineService.queryById(id);
        return R.success(medicine);
    }

    /**
     * 新增数据
     *
     * @param medicine 实体
     * @return 新增结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Medicine", name = "medicine", value = "实体", required = true)
    })
    @ApiOperation(value = "新增数据", notes = "新增数据", httpMethod = "POST")
    @PostMapping
    public R add(@RequestBody Medicine medicine) {
        boolean result = this.medicineService.insert(medicine);
        if (!result) {
            return R.error("添加失败");
        }
        return R.success("添加成功");
    }

    /**
     * 编辑数据
     *
     * @param medicine 实体
     * @return 编辑结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "Medicine", name = "medicine", value = "实体", required = true)
    })
    @ApiOperation(value = "编辑数据", notes = "编辑数据", httpMethod = "PUT")
    @PutMapping
    public R edit(@RequestBody Medicine medicine) {
        boolean result = this.medicineService.updateById(medicine);
        if (!result) {
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "删除数据", notes = "删除数据", httpMethod = "DELETE")
    @DeleteMapping("/delete/{id}")
    public R deleteById(@PathVariable Long id) {
        boolean result = this.medicineService.deleteById(id);
        if (!result) {
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }


    @ApiOperation(value = "获取详情", notes = "获取详情")
    @Transactional
    @PostMapping("/addOrUpdate")
    public R sightDetail(@RequestBody Medicine medicine) {

        //添加
        if (medicine.getId() == null || medicine.getId() == 0) {
            boolean save = medicineService.save(medicine);
            if (!save) {
                return R.error("添加失败，请重新尝试");
            }
            return R.success("添加成功");
        }
        //修改
        boolean update = medicineService.updateById(medicine);
        if (!update) {
            return R.error("修改失败，请重新尝试");
        }
        return R.success("修改成功");
    }

    /**
     * 改变药品是否是处方药
     *
     * @param mid:
     * @param state:
     * @return R
     * @author Sakura
     * @date 2023/11/29 16:06
     */
    @PutMapping("/changeState/{mid}/{state}")
    public R changeState(@PathVariable("mid") long mid,
                         @PathVariable("state") int state) {
        Medicine medicine = medicineService.getById(mid);
        if (state == 1) {
            medicine.setIsPrescription(0);
        } else {
            medicine.setIsPrescription(1);
        }
        boolean update = medicineService.updateById(medicine);
        if (!update) {
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    /**
     * 根据种类id获取药品列表
     * @param cid:
     * @return R
     * @author Sakura
     * @date 2023/12/1 21:22
     */
    @ApiOperation(value = "根据种类id获取药品列表", notes = "根据种类id获取药品列表")
    @GetMapping("getByCategory/{cid}")
    public R getByCategory(@ApiParam(value = "种类id",required = true) @PathVariable Long cid) {
        LambdaQueryWrapper<Medicine> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Medicine::getCategoryId, cid);
        List<Medicine> medicineList = medicineService.list(wrapper);
        return R.success(medicineList);
    }
    /**
     * 获取所有分类的所有药品
     * @return R
     * @author Sakura
     * @date 2023/12/1 21:22
     */
    @ApiOperation(value = "获取所有分类的所有药品", notes = "获取所有分类的所有药品")
    @GetMapping("/group/medicine")
    public R groupMedicine() {
        List<Medicine> medicineList = medicineService.list();
        Map<Long, List<Medicine>> collect = medicineList.stream().collect(Collectors.groupingBy(Medicine::getCategoryId));
        List<CategoryMedicineVO> voList = new ArrayList<>();
        for (Map.Entry<Long, List<Medicine>> listEntry : collect.entrySet()) {
            Long key = listEntry.getKey();
            Category category = categoryService.getById(key);
            CategoryMedicineVO vo = new CategoryMedicineVO();
            BeanUtils.copyProperties(category, vo);
            vo.setMedicines(listEntry.getValue());
            voList.add(vo);
        }
        return R.success(voList);
    }

    @ApiOperation(value = "获取搜索相关药品", notes = "获取搜索相关药品")
    @GetMapping("/search/{value}")
    public R getSearchGoods(@PathVariable String value) {
        LambdaQueryWrapper<Medicine> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(value),Medicine::getName,value).or().like(!StringUtils.isEmpty(value),Medicine::getContent,value);
        List<Medicine> list = medicineService.list(queryWrapper);
        return R.success(list);
    }

}
